package com.bw.session.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bw.common.constants.TokenConstants;
import com.bw.common.domain.User;
import com.bw.common.utils.JwtUtils;
import com.bw.common.utils.StringUtils;
import com.bw.session.domain.Equipment;
import com.bw.session.domain.Scheduled;
import com.bw.session.domain.dto.SessionDTO;
import com.bw.session.domain.po.BuildingsPO;
import com.bw.session.domain.po.RegionPO;
import com.bw.session.domain.po.ScheduledPO;
import com.bw.session.domain.po.SessionPO;
import com.bw.session.domain.vo.BuildingsVO;
import com.bw.session.domain.vo.RegionVO;
import com.bw.session.domain.vo.SessionVO;
import com.bw.session.exception.BizException;
import com.bw.session.mapper.SessionMapper;
import com.bw.session.service.SessionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class SessionServiceImpl implements SessionService {

    @Autowired
    private SessionMapper sessionMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;

    /**
     * 会议室列表
     * @param sessionName
     * @return
     */
    @Override
    public List<SessionVO> getSessionAll(String sessionName) {

        List<SessionPO> allSessions = sessionMapper.getAllSessions(sessionName);
        List<ScheduledPO> allScheduled = sessionMapper.getAllScheduled();

        ArrayList<SessionVO> sessionVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(allSessions)){
            for (SessionPO allSession : allSessions) {
                for (ScheduledPO scheduledPO : allScheduled) {

                    Long id = allSession.getId();
                    Long sessionId = scheduledPO.getSessionId();
                    if (id.equals(sessionId)){
                        if (scheduledPO.getScheduledStatus() == 1){
                            allSession.setSessionStatus(0L);
                        }

                        if (scheduledPO.getScheduledStatus() == 0){
                            allSession.setSessionStatus(1L);
                        }
                    }

                    if (!id.equals(sessionId)){
                        allSession.setSessionStatus(1L);
                    }

                    SessionVO sessionVO = new SessionVO();
                    BeanUtils.copyProperties(allSession,sessionVO);
                    sessionVOS.add(sessionVO);
                }
            }
        }
        return sessionVOS;
    }

    /**
     * 新增会议室
     * @param sessionDTO
     */
    @Transactional
    @Override
    public void insertSession(SessionDTO sessionDTO) {

        if (StringUtils.isEmpty(sessionDTO.getSessionName())){
            throw new BizException("会议室名称不能为空");
        }
        if (sessionDTO.getBuildingsId() == null){
            throw new BizException("会议室区域不能为空");
        }
        if (StringUtils.isEmpty(sessionDTO.getAddress())){
            throw new BizException("会议室位置不能为空");
        }
        if (sessionDTO.getHoldPerson() == null){
            throw new BizException("会议室容纳人数不能为空");
        }
        if (sessionDTO.getRegionId() == null){
            throw new BizException("会议室楼栋不能为空");
        }
        if (sessionDTO.getEquipmentIds() == null){
            throw new BizException("会议室设备不能为空");
        }
        if (sessionDTO.getStatus() == null){
            throw new BizException("会议室状态不能为空");
        }

        sessionMapper.insertSession(sessionDTO);

        sessionMapper.insertSessionEquipment(sessionDTO.getId(),sessionDTO.getEquipmentIds());

    }

    /**
     * 获取所有区域信息
     */
    @Override
    public List<BuildingsVO> selectBuildingsInfo() {
        List<BuildingsPO> buildingsPOS = sessionMapper.selectBuildingsInfo();
        ArrayList<BuildingsVO> buildingsVOS = new ArrayList<>();
        buildingsPOS.forEach(buildingsPO -> {
            BuildingsVO buildingsVO = new BuildingsVO();
            BeanUtils.copyProperties(buildingsPO,buildingsVO);
            buildingsVOS.add(buildingsVO);
        });
        return buildingsVOS;
    }

    /**
     * 获取每个区域下的楼栋信息
     */
    @Override
    public List<RegionVO> selectRegionByBuildingsId(Long buildingsId) {
        List<RegionPO> regionPOS = sessionMapper.selectRegionByBuildingsId(buildingsId);
        ArrayList<RegionVO> regionVOS = new ArrayList<>();
        regionPOS.forEach(regionPO -> {
            RegionVO regionVO = new RegionVO();
            BeanUtils.copyProperties(regionPO,regionVO);
            regionVOS.add(regionVO);
        });
        return regionVOS;
    }

    @Override
    public List<Equipment> selectAllEquipment() {
        return sessionMapper.selectAllEquipment();
    }

    @Override
    public SessionVO selectSessionById(Long id) {
        if (id == null){
            throw new BizException("该会议室已不存在");
        }
        SessionPO sessionPO = sessionMapper.selectSessionById(id);
        SessionVO sessionVO = new SessionVO();
        BeanUtils.copyProperties(sessionPO,sessionVO);
        return sessionVO;
    }

    @Transactional
    @Override
    public void update(SessionDTO sessionDTO) {
        if (StringUtils.isEmpty(sessionDTO.getSessionName())){
            throw new BizException("会议室名称不能为空");
        }
        if (sessionDTO.getBuildingsId() == null){
            throw new BizException("会议室区域不能为空");
        }
        if (StringUtils.isEmpty(sessionDTO.getAddress())){
            throw new BizException("会议室位置不能为空");
        }
        if (sessionDTO.getHoldPerson() == null){
            throw new BizException("会议室容纳人数不能为空");
        }
        if (sessionDTO.getRegionId() == null){
            throw new BizException("会议室楼栋不能为空");
        }
        if (sessionDTO.getEquipmentIds() == null){
            throw new BizException("会议室设备不能为空");
        }
        if (sessionDTO.getStatus() == null){
            throw new BizException("会议室状态不能为空");
        }

        sessionMapper.updateSession(sessionDTO);
        sessionMapper.deleteSessionEquipment(sessionDTO.getId());
        sessionMapper.insertSessionEquipment(sessionDTO.getId(),sessionDTO.getEquipmentIds());

    }

    /**
     * 根据地区分页查询会议室预约情况
     * @param sessionVO
     * @return
     */
    @Override
    public PageInfo<SessionVO> selectSessionByBuildingsId(SessionVO sessionVO) {
        PageHelper.startPage(sessionVO.getPageNum(),sessionVO.getPageSize());
        List<SessionVO> sessionVOS = sessionMapper.selectSessionByBuildingsId(sessionVO.getBuildingsId());
        PageInfo<SessionVO> sessionVOPageInfo = new PageInfo<>(sessionVOS);
        return sessionVOPageInfo;
    }

    /**
     * 查看当前会议室的预约信息和情况，自己的会议预约记录可以有取消按钮
     * @return
     */
    @Override
    public List<Scheduled> selectScheduledInfo(Scheduled scheduled) {
        List<Scheduled> scheduleds = sessionMapper.selectScheduledInfo(getUserInfo().getId(), scheduled.getSessionId());
        return scheduleds;
    }

    public User getUserInfo(){
        String token = request.getHeader("token");
        String userKey = JwtUtils.getUserKey(token);
        String userInfo = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return JSONObject.parseObject(userInfo,User.class);
    }

}
